package rma.flp;

import java.util.List;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.google.appengine.api.users.UserService;

/**
 * Sends an email with all the user's images attached
 * to a specified address. 
 */
@Controller
public class SendEmailController {

	JavaMailSender javaMailSender;
	PictureRepository pictureRepository;
	UserService userService;

	@Autowired
	public SendEmailController(JavaMailSender javaMailSender, PictureRepository pictureRepository, UserService userService) {
		this.javaMailSender = javaMailSender;
		this.pictureRepository = pictureRepository;
		this.userService = userService;
	}
	
	@RequestMapping("/send")
	public String sendEmail(@RequestParam("address") final String address) {
		String email = userService.getCurrentUser().getEmail();
		final List<Picture> pictures = pictureRepository.findByOwnerEmail(email);

		MimeMessagePreparator preparator = new MimeMessagePreparator() {
			public void prepare(MimeMessage mimeMessage) throws MessagingException {
				MimeMessageHelper message = new MimeMessageHelper(mimeMessage, MimeMessageHelper.MULTIPART_MODE_MIXED, "UTF-8");
				message.setFrom("peter.backlund@gmail.com");
				message.setTo(address);
				message.setSubject("Feeling Lucky Pictures delivered!");
				/* 
				 * A message without a body won't be delivered 
				 * and you'll get an exception like this:
				 *
				 * Failed message 1: javax.mail.SendFailedException: 
				 *   Send failure (javax.mail.MessagingException: Illegal Arguments 
				 *     (java.lang.IllegalArgumentException: Bad Request: )):
				 */
				message.setText("Here are you Feeling Lucky Pictures. Thanks for using our service!");	
				
				for (Picture picture : pictures) {
					message.addAttachment(picture.getFilename(), new ByteArrayResource(picture.getBytes()));
				}
		    }
		};

		javaMailSender.send(preparator);

		return "redirect:gallery";
	}
	
}
